/*
 * Copyright (C) 2010 Yury Kudryashov.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package name.kudryashov.base;

public final class Argument {

    private Argument() {}

    /**
     * Checks if the provided argument is null.
     * <p>
     * Example:
     * <p>
     * <tt>
     * this.param =  requireNotNull(param);
     * </tt>
     * @param arg value to check
     * @param <T> type of the argument
     * @return the argument itself
     * @throws NullPointerException if {@code arg} is null
     */
    public static <T> T requireNotNull(T arg) {
        if(arg == null) throw new NullPointerException();
        return arg;
    }

    /**
     * Checks if the provided argument is null.
     * <p>
     * Example:
     * <p>
     * <tt>
     * this.param =  requireNotNull(param, "param");
     * </tt>
     * @param arg value to check
     * @param argName  name of the parameter, used to construct an error message if the value is null
     * @param <T> type of the parameter
     * @return the argument itself
     * @throws NullPointerException if {@code arg} is null
     */
    public static <T> T requireNotNull(T arg, String argName) {
        if(arg == null) {
            throw new NullPointerException("Argument " + argName + " is null");
        }
        return arg;
    }

    /**
     * Checks if the provided condition is true and throws an exception if not.
     * @param condition condition to check
     * @param message message to throw exception with if condition is false
     * @throws IllegalArgumentException condition is false
     */
    public static void require(boolean condition, String message) {
        if(!condition) throw new IllegalArgumentException(message);
    }

    /**
     * Return the given param if condition is true and throws an exception if not.
     * @param param parameter to return if condition is true
     * @param condition condition to check
     * @param message message to throw exception with if condition is false
     * @throws IllegalArgumentException condition is false
     * @return the given parameter
     */
    public static <T> T require(T param, boolean condition, String message) {
        if(!condition) throw new IllegalArgumentException(message + "; value=" + param);
        return param;
    }

}
